import os
import subprocess


class AndroidDevice:
    def __init__(self, id=None, name=None, infos: str = None):
        if infos:
            items = infos.split()
            self.id = items[0]
            self.name = items[1]
        else:
            self.id = id
            self.name = name

        self.adb = AdbTools(self)
        self.adb.shell('shell date')

    def __str__(self):
        return self.id + ' ' + self.name


class AdbTools:
    def __init__(self, android_dev: AndroidDevice):
        self.devInfo = android_dev

    def shell(self, command: str):
        cmd = 'adb -s %s %s' % (self.devInfo.id, command)
        print(self.devInfo, '>>', command)
        result = os.popen(cmd)
        result = result.readlines()
        return_value = ''.join(str(ret + '\t') for ret in result)
        # print(self.devInfo, '<<', status, return_value)
        return return_value

    @staticmethod
    def devices():
        result = os.popen('adb devices')
        result = result.readlines()
        ADevs = []
        if len(result) > 1:
            devs = result[1:-1]  # remove header and tail
            for dev in devs:
                print(dev)
                ADevs.append(AndroidDevice(infos=dev))
        return ADevs
